from datetime import datetime
import random
import re

from flask import abort, jsonify
from flask import current_app
from flask import json
from flask import make_response
from flask import request
from flask import session

from info import constants, db
from info import redis_store
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.response_code import RET
from . import passport_blu
from info.utils.captcha.captcha import captcha

@passport_blu.route('/logout')
def logout():
    # 退出登录
    session.pop('user_id',None)
    session.pop('mobile',None)
    session.pop('nick_name',None)
    session.pop('is_admin',None)
    return jsonify(errno = RET.OK,errmsg = '退出成功')

@passport_blu.route('/login',methods = ['POST'])
def login():
    # 完成后端登录逻辑
    # 获取请求参数
    # 进行参数校验
    # 校验成功保存登录状态以及保存最后一次登录时间
    params = request.json
    mobile = params.get('mobile')
    password = params.get('password')
    if not all([mobile,password]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')
    try:
        user = User.query.filter_by(mobile = mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询错误')

    if not user:
        return jsonify(errno = RET.USERERR,errmsg = '用户不存在')

    if not user.check_password(password):
        return jsonify(errno = RET.PWDERR,errmsg = '密码错误')

    session['user_id'] = user.id
    session['user_mobile']=user.mobile
    session['nick_name'] = user.nick_name
    user.last_login = datetime.now()
    # try:
    #     db.session.commit()
    # except Exception as e:
    #    current_app.logger.error(e)
    return jsonify(errno = RET.OK,errmsg = '登录成功')



@passport_blu.route('/register',methods = ['POST'])
def register():
    # 注册逻辑的实现
    # 获取表单数据:mobile,sms_code,password
    params = request.json
    # mobile = params.get('mobile')
    mobile = params['mobile']
    sms_code = params.get('smscode')
    password = params.get('password')
    if not all([params,mobile,sms_code]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(errno = RET.PARAMERR,errmsg = '手机号码格式错误')

    db_user = User.query.filter_by(mobile=mobile).first()
    # print(db_user)
    if db_user:
        return jsonify(errno = RET.PARAMERR,errmsg = '已经注册过')

    try:
       real_sms_code = redis_store.get('SMS_'+mobile)
    except Exception as  e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据库查询错误')
    if not real_sms_code:
        return jsonify(errno = RET.NODATA,errmsg = '验证码失效')

    if real_sms_code != sms_code:
        return jsonify(errno = RET.DATAERR,errmsg = '验证码输入错误')



    user = User()
    user.mobile = mobile
    user.password = password
    user.nick_name = mobile
    user.last_login = datetime.now()
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据保存失败')

    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.mobile

    return jsonify(errno = RET.OK,errmsg = '注册成功')





@passport_blu.route('/sms_code',methods = ['POST'])
def send_sms_code():
    # 提交数据使用post 请求
    # 处理请求,接受数据
    # 将请求的数据进行校验,1.看是否存在2.判断手机号码是否正确3.图片验证码是否正确
    # 生成一个6位数的短信验证码
    # 使用云通讯将验证码发送给用户
    # 将发送的验证码保存到redis数据库
    # 将请求结果进行返回给ajax进行处理

    request_dict = request.json # 将json字符串格式数据转化成字典对象
    mobile = request_dict.get('mobile')
    image_code_id = request_dict.get('image_code_id')
    image_code = request_dict.get('image_code')

    if not all([mobile,image_code_id,image_code]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数有误')

    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(errno = RET.PARAMERR,errmsg = '手机号格式不正确')

    try:
       real_image_code= redis_store.get('ImageCodeId_'+image_code_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码已过期")


    if real_image_code.upper() != image_code.upper():
        return jsonify(errno = RET.DATAERR,errmsg = '验证码输入错误')

    sms_code_str = '%06d' % random.randint(0,999999)
    print(sms_code_str)
    # result = CCP().send_template_sms(mobile,[sms_code_str, constants.SMS_CODE_REDIS_EXPIRES / 5], "1")
    result = 0
    if result != 0:
        return jsonify(errno = RET.THIRDERR,errmsg = '发送短信失败')
    try:
        redis_store.set("SMS_" + mobile, sms_code_str, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据保存失败')

    return jsonify(errno = RET.OK,errmsg = '数据发送成功')


@passport_blu.route('/image_code')
def get_image_code():
    # 请求数据用get请求
    # 对get请求进行响应
    # 1.获取url ?后面的参数
    # 2.对参数进行校验
    # 3.调用图片生成方法,生成一张图片
    # 4.将获取的参数和生成的图片内容进行redis存储
    # 5.将图片进行返回
    image_code_id = request.args.get('imageCodeId','None')
    if not image_code_id:
        return abort(403)
    name,text,image = captcha.generate_captcha()
    try:
        redis_store.set('ImageCodeId_'+image_code_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e :
        current_app.logger.error(e)
        abort(500)
    print(text)
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'

    return response




